/**
 * 
 */
package at.fhj.ase.data;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * ASE10 - SS2011 
 * Project work Client Architecture and Design
 *  
 * @author Henning Diepold
 * @author Dieter Steiner
 */

public class AccountDAOImpl implements AccountDAO{
	
	private final String JDBC_CONNECT_STRING = "jdbc:mysql://localhost:3306/tinybank";
	private final String USERNAME = "test";
	private final String PASSWORD = "test";

	public AccountDAOImpl() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void insert(Account account) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void update(Account account) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void delete(Account account) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public Account findByID(int pKey) throws ClassNotFoundException{
		if(null == (Integer)pKey) {
			throw new NullPointerException("id: not null!");
		}
		
		final String SQL = "select id, sum_amount, banksId, customersId from accounts where id = ?";
		
		Class.forName("com.mysql.jdbc.Driver");
		
		try{
			Connection connection = DriverManager.getConnection(JDBC_CONNECT_STRING, USERNAME, PASSWORD);
			PreparedStatement ps = connection.prepareStatement(SQL);
			ps.setLong(1,pKey);
			ResultSet rs = ps.executeQuery();
			
			while (rs.next()) {
				System.out.println("> id:  " + pKey + "\n");
				System.out.println("> sum_amount: " + rs.getLong(2));
			}
			if(rs.first()) {
				return new Account(rs.getInt(1), rs.getLong(2), rs.getInt(3), rs.getInt(4));
			}
			else {
				return null;
			}
	
		}
		catch(SQLException sqlEx) {
			System.err.println(sqlEx.getMessage());
			return null;
		}
	}

	@Override
	public List<Account> findAll() {
		// TODO Auto-generated method stub
		return null;
	}
	
	protected int intRangeCheck(long value) 
	throws ArithmeticException
{
	if ((value < Integer.MIN_VALUE) || (value > Integer.MAX_VALUE))
	{
		throw new ArithmeticException("Integer overflow");
	}
	return (int) value;
}

}
